package com.dashu.authority.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dashu.authority.common.Constant;
import com.dashu.authority.entity.User;
import com.dashu.authority.servie.AuthenticationInfoService;
import com.dashu.authority.servie.UserService;
import com.dashu.authority.util.Md5Util;
import com.dashu.authority.util.ReturnJsonUtil;



@Controller
@RequestMapping("/loginController")
public class LoginController extends BaseController {
	
	@Resource
	private UserService userService;
	
	@Resource
	private AuthenticationInfoService infoService;

	@RequestMapping("/login")
	public ResponseEntity<Map<Object, Object>> Login(String loginId,
			String passWord,String redirectURL,String communityCode, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<Object, Object> rm = new HashMap<Object, Object>();
		if (loginId == null || "".equals(loginId.trim()) || passWord == null
				|| "".equals(passWord.trim())) {
			rm.put("status", 0);
			rm.put("content", "用户名，密码不能为空");
		}
		User user = userService.checkUserAndPassowrd(loginId,Md5Util.Md5(passWord));
		if (user != null) {
			String token = infoService.insertEntity(loginId, communityCode);
			rm.put("status", 1);
			rm.put("data", user);
			rm.put(Constant.AUTH_TOKEN_PARAM_NAME, token);
		} else {
			rm.put("status", 0);
			rm.put("content", "用户不存在或者用户名 密码错误");
		}
		return ReturnJsonUtil.bindResultResponseEntity(rm);
	}
//
//	public static boolean checkLogin(String token) {
//		try {
//			String returnMsg = UserHelperUtil.checkToken(token);
//			JSONObject jsonObject=JsonUtil.jsonStr2Json(returnMsg);
//			if ("0".equals(jsonObject.get("data").toString())) {
//				Map<Object, Object> user = UserHelperUtil.getLoginUser();
//				if(user==null || user.isEmpty()){
//					Map<Object, Object> authInfo = UserHelperUtil.getAuthInfo(token);
//					if(authInfo !=null && !authInfo.isEmpty()){
//						String loginId = (String) authInfo.get("loginId");
//						user = UserHelperUtil.getUserByUserId(loginId);
//						UserHelperUtil.setLoginUser(user);
//					}
//				}
//				return true;
//			}
//			return false;
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return false;
//	}
	
	public static Map<Object, Object> getLoginUser(HttpServletRequest request) {
		try {
//			String key =  CookieUtil.getCookie("loginkey", request);
			@SuppressWarnings("unchecked")
			Map<Object, Object> user = (Map<Object, Object>) request
					.getSession().getAttribute("User");
			if (user != null && !user.isEmpty()) {
				return user;
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
